package com.asa.login.viewmodel

import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.databinding.ObservableField
import com.alibaba.fastjson.JSONObject
import com.asa.base.BaseApplication
import com.asa.common.common.AppConstants
import com.asa.common.viewmodel.BaseNetViewModel
import com.asa.login.entity.UserInfo
import com.asa.login.model.LoginModel
import okio.Okio
import okio.buffer
import okio.sink
import java.io.File

/**
 * create By：anderson
 * on 2022/3/20
 * desc:
 */
class LoginViewModel:BaseNetViewModel<LoginModel>(){

    override fun createNetModel(): LoginModel {
        return LoginModel()
    }


    fun loginAction(userName:String?,pwd:String?) {
        if (userName.isNullOrEmpty()||pwd.isNullOrEmpty()){
            if (userName.isNullOrEmpty()){
                Toast.makeText(BaseApplication.appContext,"用户名不能为空",Toast.LENGTH_SHORT).show()
            } else{
                Toast.makeText(BaseApplication.appContext,"密码不能为空",Toast.LENGTH_SHORT).show()
            }
        } else{
            executeRequest({
                netModel.loginAction(userName,pwd)
            },{
                BaseApplication.token = it.token?:""
                BaseApplication.userId = it.id?:0
                writeUserInfo(it)
            },{code:Int,msg:String->
                Log.e("日志", "loginAction: code:${code} msg:${msg}")
            })
        }
    }

    /**
     *  将登陆信息保存到本地文件
     */
    private fun writeUserInfo(userInfo: UserInfo) {
        val file = File(BaseApplication.appContext.cacheDir, AppConstants.USERINFO_FILE_NAME)
        if (!file.exists()){
            file.createNewFile()
        }
        val sink = file.sink()
        val buffer = sink.buffer()
        buffer.writeUtf8(JSONObject.toJSONString(userInfo))
        buffer.close()
        sink.close()
    }


}